package com.itheima.tlias.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.tlias.common.Result;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器登录校验操作
 * @author
 * @version 1.0.1
 * @date 2023-04-11 14:51:28
 */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    //目标资源部方法运行前运行，返回ture：放行  返回false，不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.warn("进入了登录拦截器---->");
        //登录校验逻辑
        response.setContentType("application/json;charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        //不是
        //3.获取token
        String token = request.getHeader("token");
        //4.判断token
        if(token == null || "".equals(token)) {
            //token为空，直接拦截，响应数据
            Result result = Result.error("token不能为空");
            String resultJson = objectMapper.writeValueAsString(result);
            //告知客户端，响应给你的是一个json
            response.getWriter().write(resultJson);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token不为空，解析，解析失败，响应数据
            Result result = Result.error("token非法");
            String resultJson = objectMapper.writeValueAsString(result);
            //告知客户端，响应给你的是一个json
            response.getWriter().write(resultJson);
            return false;
        }
        //放行
        log.warn("验证成功放行");
        return true;
    }
}
